package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LQQ
 * @Date 2020/3/15 16:11
 * @Version 1.0
 */
@Service
public class WXPayServiceImpl implements WXPayService {
    @Value("${wxpay.notify_url}")
    private String notify_url;
    @Autowired
    private WXPay wxPay;

    /**
     * 统一下单的接口调用
     *
     * @param orderId
     * @param money
     * @return
     */
    public Map nativePay(String orderId, Integer money) {

        try {
            //1. 封装请求参数
            Map<String, String> map = new HashMap<>();
            map.put("body", "暴富");//商品描述
            map.put("out_trade_no", orderId);//订单id

            //钱的转换
            BigDecimal payMoney = new BigDecimal("0.01");//1分
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));//1.00分
            fen = fen.setScale(0, BigDecimal.ROUND_UP);//1分

            map.put("total_fee", String.valueOf(fen));//钱.分为单位
            map.put("spbill_create_ip", "127.0.0.1");//终端ip
            map.put("notify_url", notify_url);//回调地址,接收微信付款成功通知地址
            map.put("trade_type", "NATIVE");//交易类型

            //2. 基于wxpay完成统一下单接口的调用,并获取返回结果
            Map<String, String> result = wxPay.unifiedOrder(map);

            return result;


        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    /**
     * 基于微信查询订单
     *
     * @param orderId
     * @return
     */
    public Map queryOrder(String orderId) {
        try {

            Map<String, String> map = new HashMap<>();

            map.put("out_trade_no", orderId);//商户id

            //查询订单
            Map<String, String> resultMap = wxPay.orderQuery(map);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    /**
     * 基于微信关闭订单
     * @param orderId
     * @return
     */
    public Map closeOrder(String orderId) {

        try {
            Map<String,String> map= new HashMap<>();

            map.put("out_trade_no",orderId);//商户id

            //关闭订单,返回结果是微信给的
            Map<String, String> resultMap = wxPay.closeOrder(map);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
